package com.cyclecoder.rocketmq;

import com.sun.org.apache.xpath.internal.operations.String;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author by zhanglei
 * @Date 2021/8/18
 * 同步发送消息
 */
public class RocketmqSync {
    public static void main(String[] args) {
        try {
            producerMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void producerMessage() throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("sync_rocketmq");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();
        for(int i = 0; i < 100; i ++){
            Message message = new Message("protopic", ("测试消息"+i).getBytes(StandardCharsets.UTF_8));
            SendResult result = producer.send(message);
            System.out.println(result.getMsgId()+">>>>offsetid="+result.getOffsetMsgId());
        }
        producer.shutdown();
    }

    public static void consumerMessage() throws Exception{
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("rocketmq_consumer");
        consumer.setNamesrvAddr("localhost:9876");
        consumer.subscribe("protopic","*" );
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                System.out.println(list.size()+"listsize>>>");
                for(MessageExt messageExt : list){
                    System.out.printf("%s 接收到的消息 %s %n", messageExt.getBody().toString(), Thread.currentThread().getName());
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
    }
}
